﻿/*
 * Copyright (c) 2009, Thiago M. Sayao <thiago.sayao@gmail.com>
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 *  * Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  * Neither the name of the author nor the names of its contributors may be 
 *    used to endorse or promote products derived from this software without 
 *    specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 * POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
using System.Web.UI;
using DotNetBurner.Model;
using DotNetBurner.Core;
using DotNetBurner.Web.Settings;
using Resources;

namespace DotNetBurner
{
    public static class HtmlHelperExtensions
    {
        public static string UserLinks(this HtmlHelper helper, bool isAuthenticated, string userName)
        {
            StringBuilder b = new StringBuilder();

            var klass = new Dictionary<string, object> {{"class", "drop-menu-link"}};

            //b.Append(helper.RouteLink(Strings.Submit, "Submit", null, klass));

            if (!isAuthenticated)
            {
                b.Append(helper.RouteLink(Strings.SignUp, "Signup", null, klass));
                b.Append(helper.RouteLink(Strings.Logon, "Logon", null, klass));
            }
            else
            {
                string profile = "{0} ({1})".FormatWith(Strings.Profile, userName);
                b.Append(helper.RouteLink(profile, "Profile", null, klass));
                b.Append(helper.RouteLink(Strings.Logoff, "Logoff", null, klass));
            }

            return b.ToString();
        }

        public static string StoryTagsLinks(this HtmlHelper helper, IEnumerable<Tag> tags)
        {
            //this code could be done in one line, but this version is faster :)
            StringBuilder str = new StringBuilder();

            int count = tags.Count();
            int i = 0;

            foreach(var tag in tags)
            {
                var tagLink = helper.RouteLink(tag.Name, "Tag",
                                               new RouteValueDictionary
                                                   {
                                                       {"id", tag.TagId},
                                                       {"name", tag.Name.ConvertToUrlPath()},
                                                       {"page", 1}
                                                   },
                                               new Dictionary<string, object>
                                                   {
                                                       {"title", tag.Name.AttributeEncode()}
                                                   });
                str.Append(tagLink);

                if (count != i + 1)
                    str.Append(", ");

                i++;
            }

            return str.ToString();
        }

        public static string StoryVoteLink(this HtmlHelper helper, bool hasVoted, int storyId, int voteCount)
        {
            if (hasVoted)
                return String.Format("<div id=\"vote{0}\" class=\"ed\">{1}</div>", storyId, Strings.Voted);

            return
                String.Format(
                    "<div id=\"vote{0}\" class=\"it\"><a href=\"javascript:void(0)\" title=\"{1}\" onclick=\"Story.vote({2}, {3})\">{4}</a></div>",
                    storyId, Strings.ClickToVote, storyId, voteCount, Strings.Vote);
        }

        public static string GetVoteImages (this HtmlHelper helper, int voteCount)
        {
            StringBuilder r = new StringBuilder ();

            String votes = voteCount.ToString (CultureInfo.InvariantCulture);

            for (int i = 0 ; i < votes.Length ; i++)
                r.AppendFormat ("<span class=\"n{0}\"></span>", votes[i]);

            return r.ToString ();
        }

        public static string GenerateCaptcha(this HtmlHelper helper)
        {
            //TODO: Make theme configurable
            var captchaControl = new Recaptcha.RecaptchaControl  
            {  
                ID = "recaptcha",
                Theme = "white",  
                PublicKey = CaptchaSettings.Settings.PublicKey,
                PrivateKey = CaptchaSettings.Settings.PrivateKey
            };  
          
            var htmlWriter = new HtmlTextWriter(new StringWriter());  
          
            captchaControl.RenderControl(htmlWriter);  
          
            return htmlWriter.InnerWriter.ToString();  
        }

        public static string Tags(this HtmlHelper helper, IEnumerable<Tag> tags)
        {
            StringBuilder str = new StringBuilder();

            int maxPerRow = StorySettings.Settings.TagsPerPage / 5; //5 columns

            str.Append("<div class=\"tag-column\">");

            int count = 0;
            foreach (var tag in tags)
            {
                if (count > 0 && count % maxPerRow == 0)
                {
                    str.Append("</div>");
                    str.Append("<div class=\"tag-column\">");
                }

                var tagLink = helper.RouteLink(tag.Name, "Tag", new RouteValueDictionary 
                                                                 {
                                                                      {"id", tag.TagId},
                                                                      {"name", tag.Name.ConvertToUrlPath()},
                                                                      {"sort", SwissKnife.GetSortString(0)},
                                                                      {"page", 1}
                                                                 },
                                                                 new Dictionary<string, object>
                                                                 {
                                                                     {"class", "tag"}
                                                                 });

                str.AppendFormat("<h3>{0}&nbsp;&times;&nbsp;<span>{1}</span></h3>", tagLink, tag.StoryCount);
                count++;
            }

            str.Append("</div>");
            str.Append("<br style=\"clear: both\" />");

            return str.ToString();
        }
    }
}
